const crypto = require('crypto')

function v1 ({ headers, data }) {
  const normalizedData = {}
  normalizedData.event = headers['x-coding-event']
  if (json.ref) {
    normalizedData.branch = json.ref.split('/').slice(-1)[0]
  }
  if (json.token) {
    normalizedData.token = json.token
  }
  return normalizedData
}

function v2 ({ headers, data }) {
  const normalizedData = {}
  normalizedData.event = headers['x-coding-event']
  if (json.ref) {
    normalizedData.branch = json.ref.split('/').slice(-1)[0]
  }
  if (headers['x-coding-signature']) {
    normalizedData.token = function (salt) {
      const sha1 = crypto.createHmac('sha1', salt).update(data).digest('hex')
      return `sha1=${sha1}` === headers['x-coding-signature']
    }
  }
  return normalizedData
}

module.exports = function ({ headers, data }) {
  json = JSON.parse(data)

  if (headers['x-coding-webhook-version'] != 'v2') {
    return v1({ headers, data })
  } else {
    return v2({ headers, data })
  }
}
